import json

from flask import Flask, url_for, request, Blueprint, jsonify, g, redirect, render_template
from flaskr.db import get_db
from flaskr import user

bp = Blueprint('duid', __name__, url_prefix='/duid')

def get_next_duid():
    db = get_db()
    duid_assigned_max = db.execute(
        'SELECT * FROM duids_assignment where duid=(select max(duid) from duids_assignment)').fetchone()
    duid_next_assign = 0 if duid_assigned_max is None else (1 + int(duid_assigned_max['duid']))

    return duid_next_assign

def get_recent_duid_records(count):
    db = get_db()
    duid_db_records = db.execute('SELECT * FROM duids_assignment').fetchall()

    duid_records = []
    for duid_db_record in duid_db_records[-count:]:
        duid_records.append("duid:%d,\tused:%d,\tdt:%s,\taccount:%s" % (duid_db_record['duid'], duid_db_record['used'], duid_db_record['datetime'], duid_db_record['account']))

    return duid_records


def duid_occupy(account='', fingerprint='', license=''):
    duid_occupying = get_next_duid()
    try:
        db = get_db()
        db.execute(
            'INSERT INTO duids_assignment (duid, datetime, account, fingerprint, license) VALUES (?, datetime("now", "localtime"), ?, ?, ?)',
            (duid_occupying, account, fingerprint, license))
        db.commit()
        return duid_occupying
    except Exception as e:
        return 0

def duid_occupied(duid_used):
    try:
        db = get_db()
        db.execute('UPDATE duids_assignment SET used = 1 WHERE duid = ?', (duid_used,))
        db.commit()
        return duid_used
    except:
        return 0


@bp.route('/')
@user.login_required
def index():
    return render_template('/duid/entry.html', duid_next_assign=get_next_duid(), duid_recent_records=get_recent_duid_records(10))

#GET for querying the next available duid for the next occupation.
#POST for occupying a new duid and return it.
@bp.route('/occupy', methods=('GET', 'POST'))
@user.login_required
def occupy():
    if request.method == 'GET':
        return render_template('/duid/entry.html', duid_next_assign=get_next_duid())
    else:
        account = g.user['username']
        duid_datas = json.loads(request.get_data(as_text=True))
        fingerprint = duid_datas['fingerprint'] or ''
        license = duid_datas['license'] or ''
        duid_assigned = duid_occupy(account, fingerprint, license)
        return render_template('/duid/entry.html', duid_next_assign=get_next_duid(), duid_assigned=duid_assigned)

#to tell that the duid specified was used.
@bp.route('/occupied', methods=('POST',))
@user.login_required
def occupied():
    raw_datas  = request.get_data(as_text=True)
    duid_datas = json.loads(raw_datas)
    duid_used = duid_datas['duid'] or '0'
    return render_template('/duid/entry.html', duid_used=duid_occupied(duid_used))



#GET for querying the next available duid for the next occupation.
#POST for occupying a new duid and return it.
@bp.route('/simple_occupy', methods=('GET', 'POST'))
@user.login_required_ret(nologin={"duid": 0})
def simple_occupy():
    if request.method == 'GET':
        return jsonify({"duid": get_next_duid(),})
    else:
        account = g.user['username']
        duid_datas = json.loads(request.get_data(as_text=True))
        fingerprint = duid_datas['fingerprint'] or ''
        license = duid_datas['license'] or ''
        return jsonify({"duid": duid_occupy(account, fingerprint, license),})


#to tell that the duid specified was used.
@bp.route('/simple_occupied', methods=('POST',))
@user.login_required_ret(nologin={"duid": 0})
def simple_occupied():
    raw_datas  = request.get_data(as_text=True)
    duid_datas = json.loads(raw_datas)
    duid_used = duid_datas['duid'] or '0'
    return jsonify({"duid": duid_occupied(duid_used),})


@bp.route('/deprecated_occupy', methods=('GET', 'POST'))
def deprecated_occupy():
    if request.method == 'GET':
        return jsonify({"duid": get_next_duid(),})
    else:
        account = 'Deprecated'
        duid_datas = json.loads(request.get_data(as_text=True))
        fingerprint = duid_datas['user'] or ''
        license = duid_datas['remark'] or ''
        return jsonify({"duid": duid_occupy(account, fingerprint, license),})

@bp.route('/deprecated_occupied', methods=('POST',))
def deprecated_occupied():
    raw_datas  = request.get_data(as_text=True)
    duid_datas = json.loads(raw_datas)
    duid_used = duid_datas['duid'] or '0'
    return jsonify({"duid": duid_occupied(duid_used),})